﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TlvLib.SiChuan.Packet;


namespace TlvLib.SiChuan.Unpacker
{
    static class RegistrationUnpacker
    {
        public static bool TryUnpack(byte[] buffer, out RegistrationReply packet)
        {
            packet = null;
            if (!Helper.IsValid(buffer))
            {
                return false;
            }

            var type = Helper.GetPacketType(buffer);
            if (type != PacketType.Registration)
            {
                return false;
            }

            var accessCodeCount = Helper.CountUptoWhiteSpace(buffer, 8, 32);
            var accessCode = Configuration.TextEncoding.GetString(buffer, 8, accessCodeCount);
            var succeedCode = Configuration.EndianBitConverter.ToInt16(buffer, 40);
            var succeed = succeedCode == 1 || succeedCode == 2;

            var ipCount = Helper.CountUptoWhiteSpace(buffer, 42, 48);
            var ip = Configuration.TextEncoding.GetString(buffer, 42, ipCount);
            if (string.IsNullOrEmpty(ip) && succeedCode == 1)
            {
                return false;
            }
            //ip = "192.168.1.10";
            var port = Configuration.EndianBitConverter.ToInt32(buffer, 90);
            if (port <= 0 && succeedCode == 1)
            {
                return false;
            }
            //port = 8887;
            var failCode = Configuration.EndianBitConverter.ToInt16(buffer, 94);

            packet = new RegistrationReply() { AccessCode = accessCode, FailReason = failCode, Ip = ip, Port = port, Succeed = succeed };
            return true;
        }
    }
}
